<?php

namespace Biz\model\settlement;

use Doraemon\pockets\datebase\BaseDbModel;
use Medoo\Medoo;


class SettlementAccount extends BaseDbModel
{

    const _CONFIG_FILE_ = 'db_shop';

    const _CONFIG_SELECT_ = 'db_settlement';

    const _DATABASE_ = 'shop_settlement';

    const _TABLE_NAME = 'settlement_account';

    public static function getAccountInfo($shopId)
    {
        $info = self::get(['shop_id', 'balance', 'withdrawal_amount'], ['shop_id' => $shopId]);
        return $info;
    }

    /**
     * 更改结算账户余额（及累计提现金额）
     * @param $shopId 店铺id
     * @param $amount 更改的金额
     * @param bool $changeWithdrawalAmount 是否更改累计提现金额
     * @return bool
     * @throws \Exception
     */
    public static function updateBalance($shopId, $amount, $changeWithdrawalAmount = false)
    {
        $info = self::select_master("*", Medoo::raw(' where shop_id=:shopId for update', [':shopId' => $shopId]));
        $info = array_shift($info);
        if ($info) {
            $data = [
                'balance' => $info['balance'] + $amount,
            ];
            if ($changeWithdrawalAmount) {
                $data['withdrawal_amount'] = $info['withdrawal_amount'] + abs($amount);
            }
            $ret = self::update($data, ['shop_id' => $shopId]);
        } else {
            $data = [
                'shop_id' => $shopId,
                'balance' => $amount
            ];
            if ($changeWithdrawalAmount) {
                $data['withdrawal_amount'] = $info['withdrawal_amount'] + abs($amount);
            }
            $ret = self::insert($data);
        }
        if ($ret->errorCode() !== '00000') {
            throw new \Exception('数据库操作错误');
        }
        return true;
    }
}
